
<template>
  <div class="app-container">

    <div class="filter-container">
      改善题目：<el-input v-model="listQuery.improvetitle" placeholder="improvetitle" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

    </div>

    <!-- Note that row-key is necessary to get a correct row order. -->
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">

      <el-table-column width="180px" align="center" label="改善计划编号">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.dimpId }}</span></template>

      </el-table-column>
      <el-table-column min-width="300px" label="题目">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.improvetitle }}</span></template>
      </el-table-column>

      <el-table-column width="100px" label="登录时间">

        <template slot-scope="scope">
          <span>{{ scope.row.createDate }}</span></template>
      </el-table-column>
      <el-table-column width="100px" label="调查时间">

        <template slot-scope="scope">
          <span>{{ scope.row.inquiryDate }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="登录人员" width="95">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.createUser.userName }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="发生地点" width="95">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.happenLocation }}</span></template>
      </el-table-column>
      <el-table-column class-name="status-col" label="执行部门" width="110">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.workDepartment.deptName }}</span></template>
      </el-table-column>

      <el-table-column align="center" label="裁决状态" width="80" prop="">
        <template slot-scope="scope">

          <span v-if="scope.row.status==1">申请中...</span>
          <span v-if="scope.row.status==0">已删除</span>
          <span v-if="scope.row.status==2">部长已裁决</span>
          <span v-if="scope.row.status==3">部门长已裁决</span>
          <span v-if="scope.row.status==4">已驳回</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230">
        <template v-if="scope.row.status==2||scope.row.status==3" slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <!-- <el-form-item label="改善计划编号" prop="improveId">
          <el-input v-model="temp.improveId" />
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="登陆时间" prop="createDate">
              <el-date-picker v-model="temp.createDate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事故发生时间" prop="ehsDisaster">
              <el-input />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录人员" prop="createUser">
              <el-input v-model="userName" readonly="readonly" placeholder="不填" />
            </el-form-item>
            <!-- <el-form-item label="登录人员" prop="createUser">

              <el-autocomplete
                v-model="userName"
                class="el-input"
                :fetch-suggestions="userSearchAsync"
                placeholder="请输入工号"
                :trigger-on-focus="false"
                @select="handleSelectp"
              />
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="事故发生报告人姓名" prop="ehsDisaster">

              <el-input />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="调查时间" prop="inquiryDate">
              <el-date-picker v-model="temp.inquiryDate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事故发生报告人部门" prop="ehsDisaster">

              <el-input />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发生地点" prop="happenLocation">
              <el-input v-model="temp.happenLocation" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目" prop="improvetitle">
              <el-input v-model="temp.improvetitle" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="灾害预防题目" prop="disastertitle">
          <el-select v-model="temp.disid" class="filter-item" placeholder="请选择灾害预防题目">
            <el-option v-for="item in faultNameList" :key="item.disid" :label="item.title" :value="item.disid" />
          </el-select>
        </el-form-item>
        <el-form-item label="事故概要和调查结果" prop="inquiryContent">
          <markdown-editor ref="markdownEditor" v-model="temp.inquiryContent" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />

        </el-form-item>
        <el-form-item label="根本原因" prop="reason">
          <markdown-editor ref="markdownEditor" v-model="temp.reason" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />

        </el-form-item>
        <el-form-item label="改善计划" prop="plan">
          <markdown-editor ref="markdownEditor" v-model="temp.plan" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />

        </el-form-item>

        <el-form-item label="执行部门" prop="workDepartment">

          <el-autocomplete
            v-model="deptName"
            class="el-input"
            :fetch-suggestions="deptSearchAsync"
            placeholder="请输入部门"
            :trigger-on-focus="false"
            @select="handleSelectTeam"
          />
        </el-form-item>
        <el-form-item label="执行人员负责人" prop="workUser">

          <el-input v-model="temp.workUser" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'
import { fetchImproveList, deleteImproveList, editImproveList, fetchAllCount, getPersonList, getDeptList, createInquery, getFaultNameList } from '@/api/disasterImprove'
import Sortable from 'sortablejs'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getuserbyemp } from '@/api/user'
import { getDeptByName } from '@/api/fault'

// arr to obj, such as { CN : "China", US : "USA" }

export default {
  name: 'Improve',
  components: { Pagination, MarkdownEditor },
  directives: { waves },
  data() {
    return {

      list: null,
      total: 0,

      listLoading: true,
      editList: null,
      faultUserCode: null,
      faultTeam: null,
      deptName: null,
      userName: null,
      disastertitle: null,
      disasterTitle: null,
      sortable: null,
      oldList: [],
      newList: [],
      // 参数条件
      listQuery: {
        page: 1,
        limit: 20,
        faultTitle: null

      },
      personlist: null,
      deptlist: null,
      faultNameList: null,
      temp: {
        dimpId: null,
        createUser: '',
        createDate: '',
        inquiryDate: '',
        happenLocation: '',
        improvetitle: '',
        ehsDisaster: '',
        reason: '',
        plan: '',
        workDepartment: null,
        status: '',
        score: '',
        workUser: null,
        disid: '',
        inquiryContent: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        detail: '明细'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        improvetitle: [{ required: true, message: 'improvetitle is required', trigger: 'blur' }],
        createDate: [{ required: true, message: 'createDate is required', trigger: 'blur' }],
        inquiryDate: [{ required: true, message: 'inquiryDate is required', trigger: 'blur' }],
        happenLocation: [{ required: true, message: 'happenLocation is required', trigger: 'blur' }],
        reason: [{ required: true, message: 'reason is required', trigger: 'blur' }],
        plan: [{ required: true, message: 'plan is required', trigger: 'blur' }],
        inquiryContent: [{ required: true, message: 'inquiryContent is required', trigger: 'blur' }],
        workUser: [{ required: true, message: 'workUser is required', trigger: 'blur' }],
        // disastertitle: [{ required: true, message: 'disastertitle is required', trigger: 'change' }],
        workDepartment: [{ required: true, message: 'workDepartment is required', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fechData()
  },
  methods: {
    fechData() {
      // console.log('222222222222222')
      getPersonList().then(response => {
        this.personlist = response.listName
      })
      getDeptList().then(response => {
        this.deptlist = response.listName
      })
      getFaultNameList().then(response => {
        this.faultNameList = response.listName
      })
      fetchAllCount().then(response => {
        // console.log('总数量2' + response.length)
        this.total = response.count
      })
      fetchImproveList(this.listQuery).then(response => {
        this.listLoading = true

        this.list = response.ehsimproveList

        this.showList = response.ehsimproveList
        console.log('shuju ' + this.showList)
        this.listLoading = false
        this.temp.ehsDisaster = this.list.ehsDisaster
      })
    },
    async handleSelectp(u) {
      this.workUser = u.userName
      this.userId = u.userId
      // console.log(this.userId)
    },

    async handleSelect(u) {
      this.userName = u.userName

      this.userId = u.userId
      // console.log(this.userId)
    },
    async userSearchAsync(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.userName + '-' + r.userId
        tem_obj.userName = r.userName

        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async deptSearchAsync(queryString, callback) {
      var list = []
      const { deptList } = await getDeptByName(queryString)
      deptList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.deptId + '-' + r.deptName
        tem_obj.deptName = r.deptName
        tem_obj.deptId = r.deptId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async handleSelectTeam(u) {
      this.deptName = u.deptName
      this.deptId = u.deptId
      this.temp.workDepartment = '' + this.deptName
      console.log('==============================' + this.temp.workDepartment)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fechData()
    },
    handleDelete(row) {
      console.log(row)
      // alert(row.dimpId)
      deleteImproveList(row.dimpId).then(response => {
        console.log('success')
      // alert('success')
      })
      this.fechData()
    },
    handleEdit(row) {
      // alert(row.dimpId)
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp1 = Object.assign({}, row1) // copy obj
      console.log('row1' + row1.ehsDisaster.disid)
      this.temp.dimpId = this.temp1.dimpId
      this.temp.createDate = this.temp1.createDate
      this.temp.inquiryDate = this.temp1.inquiryDate
      this.temp.happenLocation = this.temp1.happenLocation
      this.temp.improvetitle = this.temp1.improvetitle
      this.temp.reason = this.temp1.reason
      this.temp.plan = this.temp1.plan
      this.temp.workUser = this.temp1.workUser
      this.temp.disid = this.temp1.ehsDisaster.disid
      // this.disastertitle = this.temp1.ehsDisaster.title
      // console.log(this.temp1.disid)
      console.log(this.temp1.ehsDisaster.title)
      this.temp.inquiryContent = this.temp1.inquiryContent
      this.temp.workDepartment = this.temp1.workDepartment
      this.userName = this.temp1.createUser.userName
      this.deptName = this.temp1.workDepartment.deptName
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // alert(this.dialogStatus)
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // alert('进入')
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            // alert(this.temp.dimpId)
            const query = { dimpId: this.temp.dimpId, workUser: query1.workUser, disid: query1.disid, inquiryContent: query1.inquiryContent, createDate: query1.createDate, inquiryDate: query1.inquiryDate, happenLocation: query1.happenLocation, improvetitle: query1.improvetitle, reason: query1.reason, plan: query1.plan, userName: this.userName, userId: this.userId, deptName: this.deptName, deptId: this.deptId }
            editImproveList(query).then(response => {
              // this.obj = response

              // console.log('修改后' + response)
              // alert('修改成功')
            })
            // 刷新页面
            location.reload()
          }
        })
      }
    },

    resetTemp() {
      this.temp = {
        dimpId: '',
        createUser: '',
        createDate: '',
        inquiryDate: '',
        happenLocation: '',
        improvetitle: '',
        ehsDisaster: '',
        reason: '',
        plan: '',
        workDepartment: '',
        status: '',
        score: '',
        disid: '',
        workUser: null,
        inquiryContent: ''

      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // alert(this.dialogStatus)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // alert(this.temp.disid)
          this.temp.author = 'vue-element-admin'

          const query = { workUser: this.temp.workUser, disid: this.temp.disid, inquiryContent: this.temp.inquiryContent, createDate: this.temp.createDate, inquiryDate: this.temp.inquiryDate, happenLocation: this.temp.happenLocation, improvetitle: this.temp.improvetitle, reason: this.temp.reason, plan: this.temp.plan, userName: this.userName, userId: this.userId, deptName: this.deptName, deptId: this.deptId }
          createInquery(query).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          location.reload()
        }
      })
    },
    handleDetail(row) {
      // alert(row)

      const row1 = JSON.parse(JSON.stringify(row))
      this.temp1 = Object.assign({}, row1) // copy obj
      // alert(this.temp.dimpId)
      this.temp.dimpId = this.temp1.dimpId
      this.temp.createDate = this.temp1.createDate
      this.temp.inquiryDate = this.temp1.inquiryDate
      this.temp.happenLocation = this.temp1.happenLocation
      this.temp.improvetitle = this.temp1.improvetitle
      this.temp.reason = this.temp1.reason
      this.temp.plan = this.temp1.plan
      this.temp.workUser = this.temp1.workUser
      this.temp.disid = this.temp1.ehsDisaster.disid
      this.disastertitle = this.temp1.ehsDisaster.title
      // console.log(this.temp1.disid)
      console.log(this.temp1.ehsDisaster.title)
      this.temp.inquiryContent = this.temp1.inquiryContent
      this.userName = this.temp1.createUser.userName

      this.deptName = this.temp1.workDepartment.deptName

      // 获取事故的信息，将信息显示

      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
